//
//  CXBFileSystemElement.m
//  CocoaXBI
//

#import "CXBFileSystemElement.h"

#import "CXBDocument.h"

@implementation CXBFileSystemElement

@synthesize children = _children;

- (id)initWithXFSElement:(XBIXFSElement *)xfsElement {
    int numberOfChildren = XBIXFSElementGetNumberOfChildren(xfsElement);
    if (self = [super init]) {
        _xfsElement = XBIXFSElementCopy(xfsElement);
        NSMutableArray * tmpChildren = [[NSMutableArray alloc] init];
        int currentChild = 0;
        for (currentChild = 0; currentChild < numberOfChildren; currentChild++) {
            CXBFileSystemElement * newChild = [[CXBFileSystemElement alloc] initWithXFSElement:XBIXFSElementGetChildrenAtIndex(xfsElement, currentChild)];
            [tmpChildren addObject:newChild];
            [newChild release];
        }
        _children = [[NSArray alloc] initWithArray:tmpChildren];
        [tmpChildren release];
    }
    return self;
}

- (void)dealloc {
    XBIXFSElementDelete(_xfsElement);
    [super dealloc];
}

- (NSString *)name {
    return [NSString stringWithUTF8String:XBIXFSElementGetName(_xfsElement)];
}

- (uint64_t)size {
    return XBIXFSElementGetSize(_xfsElement);
}

- (int)writeToFileAtURL:(NSURL *)anURL {
    XBIError error;
    int returnValue = -1;
    if ([anURL isFileURL]) {
        CXBDocument * currentDocument = [[NSDocumentController sharedDocumentController] currentDocument];
        const char * filePath = [[[anURL path] stringByAppendingPathComponent:self.name] UTF8String];
        if (filePath != NULL && currentDocument != nil) {
            FILE * destinationFile = fopen(filePath, "w");
            returnValue = XBIImageWriteXFSElementToFile(currentDocument.isoImage, _xfsElement, destinationFile, &error);
            fclose(destinationFile);
        }
    }
    return returnValue;
}

@end
